<template>
    <div class="PhysicalRoomCalendar">
        <div class="row">
            <div class="col-md-3" v-show="!showExportIcal">
                <div class="white-box">
                    <h3 class="box-title">
                        Event Sources
                        <button class="btn btn-info btn-xs pull-right" @click="copyUrl(exportUrl)">Export URL</button>
                    </h3>
                    <div class="row">
                        <div class="col-md-12 col-sm-12 col-xs-12">
                            <div id="calendar-events" class="m-t-20">
                                <div :key="'source' + index"  v-for="(source, index) in sources">
                                    <div class="calendar-events" data-class="bg-info">
                                        <i class="fif fif-circle" :style="{'color': lidsColors[source.room_id]}"></i>
                                        {{`${source.logical_room_id}(${source.name})`}}
                                        <i class="fif fif-link text-info" style="cursor: pointer;" @click="copyUrl(source.url)"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6" v-show="showExportIcal">
                <div class="white-box">
                    <div id="calendar2">
                        <full-calendar :events="exportEvents"></full-calendar>
                    </div>
                </div>
            </div>
            <div class="col-md-9" :class="{'col-md-6': showExportIcal}">
                <div class="white-box">
                    <div id="calendar">
                        <full-calendar :events="events" :priceData="priceData" value="airbnb">
                            <template slot="fc-header-left">
                                <a class="btn btn-primary" @click="showExportIcal = !showExportIcal" style="">
                                    {{showBtnText}}
                                </a>
                            </template>
                        </full-calendar>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="panel">
                    <item-table :columns="defaultColumns" :data="data" :loading="tableLoading" @sort="_sort">
                        <template slot="actions" slot-scope="props">
                            <!--<button type="button" class="btn btn-info btn-outline btn-circle btn-md m-r-5" @click="_editItem(props)">-->
                                <!--<i class="fif fif-edit"></i>-->
                            <!--</button>-->
                            <button type="button" class="btn btn-danger btn-outline btn-circle btn-md m-r-5" @click="_deleteItem(props)">
                                <i class="fif fif-delete"></i>
                            </button>
                        </template>
                    </item-table>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    // components
    import fullCalendar from '@/components/widgets/RoomCalendar/RoomCalendar'
    import ItemTable from '@/components/widgets/ItemTable'
    import ItemDetail from '@/components/widgets/ItemDetail'
    // api
    import {getRoomEvents, deleteIcal} from '@/api/event'
    import {searchModel} from "@/api/model";
    // mixin
    import {itemMixin} from '@/mixins/item'
    // config
    import columns from '@/config/columns'
    import Vue from 'vue'
    import VueClipboard from 'v-clipboard'
    Vue.use(VueClipboard)

    export default {
        name: "PhysicalRoomCalendar",
        components: {fullCalendar, ItemTable, ItemDetail},
        props: {
            pid: {
                type: String,
                default: null,
            }
        },
        mixins: [itemMixin],
        created() {
            this.colors = ['#e67e22','#f1c40f','#16a085', '#27ae60', '#2980b9','#8e44ad', '#2c3e50',
                '#95a5a6','#ecf0f1','#f39c12','#7f8c8d', '#d35400', '#c0392b']
            this.physical_room_id = this.$route.hash.length ? this.$route.params.pid + this.$route.hash : this.$route.params.pid
            this.defaultColumns = columns['Ical']
            this.originalPriceData = []
        },
        activated() {
            this.getData()
        },
        data() {
            return {
                events: [],
                exportEvents: [],
                table: null,
                data: [],
                sources: [],
                lidsColors: {},

                showBtnText: 'Open Exported View',
                showExportIcal: false,
                proom: {},

                priceData: []
            }
        },
        computed: {
            columns() {
                if (!this.table) {
                    return []
                }
                let tmp = []
                this.table.headers.forEach( item => {
                    tmp.push({
                        label: item,
                        value: true,
                        header: item,
                    })
                } )
                // actions
                tmp.unshift({
                    label: 'actions',
                    width: '100',
                    align: 'left',
                    type: 'actions',
                })
                return tmp
            }
        },
        watch: {
            showExportIcal(newVal) {
                this.showBtnText = !newVal ? 'Open Exported View': 'Close Exported View'
            },
            pid() {
                if (this.pid) {
                    this.physical_room_id = this.pid
                    this.getData()
                }
            }
        },
        methods: {
            getData() {
                searchModel("PriceCalendar", {
                    "search_keys": {"physical_room__physical_room_id": this.physical_room_id},
                    "page_size": 99999,
                }).then(res => {
                    this.priceData = res.data.list
                    this.originalPriceData = res.data.list
                })
                // 获取所有日历项
                getRoomEvents(this.physical_room_id, 'all', this.physical_room_id).then( response => {
                    this.events = []
                    this.exportEvents = []
                    this.sources = []
                    this.lidsColors = {}
                    let evt = response.data.events
                    let exportEvt = response.data.exportEvents
                    this.sources = response.data.urls
                    this.exportUrl = `http://www.funkey.asia/ical/${response.data.physical_room.id}.ics`
                   // this.table = response.data.ical
                    this.data = response.data.ical
                    this.sources.forEach((item, index) => {
                        this.lidsColors[item.room_id] = this.colors[index] ? this.colors[index] : "#e74c3c"
                    })
                    for (let i = 0; i < evt.length; i++) {
                        let eventIndex = 0
                        // 为每个事件设置index，根据index来放置每个event的位置
                        for (let index in this.events) {
                            if (this.events[index].start<=evt[i].start && this.events[index].end > evt[i].start) {
                                eventIndex = this.events[index].eventIndex + 1
                            }
                        }

                        this.events.push({
                            start: evt[i].start,
                            end: evt[i].end,
                            title: evt[i].title,
                            cssStyle: evt[i].room_id ? {'background': this.lidsColors[evt[i].room_id],'color':'#fff'} : {'background': '#dd4b39','color':'#fff'},
                            eventIndex: eventIndex
                        })
                    }

                    for (let i = 0; i < exportEvt.length; i++) {
                        this.exportEvents.push({
                            start: exportEvt[i].start,
                            end: exportEvt[i].end,
                            title: exportEvt[i].title,
                            cssClass: 'bg-aqua'
                        })
                    }
                })
            },
            copyUrl(url) {
                if (url) {
                    this.$clipboard(url)
                    $.toast({
                        heading: 'Copy Success',
                        position: 'top-right',
                        text: '',
                        icon: 'success'
                    });
                }
            },
            _editItem(props) {
                this.model = ''
                this.editItem(props)
            },
            _deleteItem(props) {
                swal({
                    title: "Are you sure?",
                    text: "Remove this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then( (willDelete)=> {
                    if (willDelete) {
                        this.tableLoading = true
                        deleteIcal([props.item.id]).then( res => {
                            this.tableLoading = false
                            if (res.data.code == 0) {
                                this.getData()
                                swal("Success", "", "success")
                            } else {
                                swal("Fail", "", "error")
                            }
                        }).catch( e =>{
                            this.tableLoading = false
                        })
                    }
                } )
            },
            _sort(dir, column) {
                column = column[0]
                dir = dir[0]
                this.data = this.data.sort((a, b) => {
                    return dir === 'descend' ? String(b[column]).localeCompare(String(a[column])) : String(a[column]).localeCompare(String(b[column]))
                })
            },
        }
    }
</script>

<style scoped>

